package com.mycom.core1;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author xp
 *         Created on 2018/2/26
 */
public class TcpServer {
    private static final Logger log = LoggerFactory.getLogger(TcpServer.class);

    public void start() throws InterruptedException {
        int portNum = Integer.parseInt((String) AppInit.config.get("server_port"));
        log.info("【TCP】服务启动中，端口号：" + portNum);
        // 配置服务端的NIO线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            //Netty的引导类，用于简化开发
            ServerBootstrap b = new ServerBootstrap();
            //把事件循环组加入引导程序
            b.group(bossGroup, workerGroup);
            //开启socket
            b.channel(NioServerSocketChannel.class);
            //加入业务控制器，这里是加入一个初始化类，其中包含了很多业务控制器
            b.childHandler(new TcpServerInitializer());

            // 服务器绑定端口监听
            ChannelFuture f = b.bind(portNum).sync();
            if (f.isSuccess()) {
                log.info("【TCP】启动netty服务成功, 端口号" + portNum);
            }

            // 等待服务器监听端口关闭
            f.channel().closeFuture().sync();
        } finally {
            //Netty优雅退出
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }


    }

}
